package com.example.springbooteasycode.zjrc.project.Koal.AAAstructure;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;

/**
 * 模拟Koal加密机数据返回
 */
public class AHSMKoalServerMain {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(8888)) {
            System.out.println("服务器已启动，监听端口 8888...");

            // 等待客户端连接（阻塞）
            try (Socket socket = serverSocket.accept()) {
                System.out.println("客户端已连接：" + socket.getInetAddress());

                // 接收客户端发送的数据
                InputStream is = socket.getInputStream();
                byte[] buffer = new byte[1024];
                int length = is.read(buffer);
                String receivedData = new String(buffer, 0, length);

                System.out.println("有效字节数: " + length);       // 输出 12
                System.out.println("有效数据: " + receivedData);   // 输出 Hello, World!
                System.out.println("数组总长度: " + buffer.length); // 输出 1024（预分配的长度）

                System.out.println("接收到的数据: " + receivedData);


                // 添加响应逻辑
                OutputStream os = socket.getOutputStream();
//                String response = "服务器已收到: " + receivedData;
                String responseStr = "00136AB7FFFFFFFFFFFFFFFF00967B94B28102C9CA";
                // 2+2+8+1+8 = 21，这个byte[]就是最终加密机返回的byte[]。！！！
                byte[] responseBytes = hexStringToByteArray(responseStr);
                //todo-选这个，是十六进制字符串转byte[]，responseBytes-1[0, 19, 106, -73, -1, -1, -1, -1, -1, -1, -1, -1, 0, -106, 123, -108, -78, -127, 2, -55, -54]
                System.out.println("responseBytes-1" + Arrays.toString(responseBytes));
                // 如果直接getBytes()，会按照一个字符一个字节的ASCII码进行编码，导致数据丢失。
//                System.out.println("responseBytes-2" + Arrays.toString(responseStr.getBytes()));
                os.write(responseBytes);
                os.flush();
                System.out.println("已发送响应: " + responseStr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    // 将十六进制字符串转为字节数组，用于处理返回报文等
    public static byte[] hexStringToByteArray(String hex) {
        int len = hex.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
        }
        return data;
    }
}
